<?php
namespace app\admin\controller;
header("content-type:text/html;charset=utf-8");
use app\admin\controller\Base;
use app\admin\model\Admin;
use app\admin\model\Apply;
use app\admin\model\Dustbin;
use app\admin\model\User;
use app\admin\model\Usertype;
use think\Db;
use think\Request;
use think\File;
class  Users extends Base
{
    //XXX级
    public function lists(Request $request){
      $arr = [
       "setting"=>$this->getAllSetting(),
       "grade" => $request->get("grade")
      ];
      return view("lists",$arr);
    }

    //所有
    public function lists5(){
      $arr = [
        "setting"=>$this->getAllSetting(),
      ];
      return view("lists5",$arr);
    }
    //获取所有学生基本信息
     public function getUser(Request $request){
       $query = $request->get(); //接收所有数据
       //分页
       $limit = empty($query["limit"]) ? 10 : $query["limit"];
       $page = empty($query["page"]) ? 1 : $query["page"];
       $start = ($page - 1) * $limit;
       unset($query['limit']);
       unset($query['page']);
       unset($query['grade']);
       //创建条件变量,如果接收到的数据是null字符串则拼接 is null 条件
       $where = true;
       foreach($query as $key=> $val){
         if(!empty($val) && trim($val) != "null" && trim($val) != "notnull") {
           $where .= " and ".$key." like '%".$val."%'";
         }elseif(trim($val) == "null"){
           $where .= " and ({$key} is null or {$key} = '') ";
         }elseif(trim($val) == "notnull"){
           $where .= " and ({$key} is not null and {$key} != '')";
         }
       }
       $sql  = "select * from user where {$where} order by grade desc limit {$start},{$limit}";
       $sqls = "select count(*) as c from user where {$where}";
       $count = collection(Db::query($sqls))->toArray();
       $data = collection(Db::query($sql))->toArray();
       foreach($data as $key=>$val){
         $data[$key]['idcard'] = $val['idcard']."\t";
         $data[$key]['sex'] = $val ? "男" : "女";
         $data[$key]['create_time'] = date("Y年m月d日 H:i:s",$val['create_time']);
       }
       //组织数据
       $arr = [
         "code" =>0,
         "msg"=>'学生信息',
         "count"=>$count[0]['c'],
         "data"=>$data
       ];
        return json($arr);
     }
   //获取基本数据
   public function getAllUser(Request $request){
     //接收数据
     $query = $request->get();
     //分页
     $limit = empty($query["limit"]) ? 10 : $query["limit"];
     $page = empty($query["page"]) ? 1 : $query["page"];
     $start = ($page - 1) * $limit;
     //
     $grade = empty($query["grade"]) ? null : $query["grade"];
     unset($query['limit']);
     unset($query['page']);
     unset($query['grade']);

     //判断是大几的学生
     $where = "user.grade = {$grade}";
     foreach($query as $key=> $val){
       if(!empty($val)) {
         $where .= " and ".$key." like '%".$val."%'";
       }
     }
     //sql语法
     $sql  = "select *,user.id as 'userid',apply.id as 'applyid',user.create_time as 'user_create_time',user.update_time as 'user_update_time',apply.create_time as 'apply_create_time',apply.update_time as 'apply_update_time',user.grade as 'user_grade',apply.id as 'apply_id' from user left join apply on apply.userid = user.id where {$where} limit {$start},{$limit}";
     $sqls = "select count(*) as c from user,apply where user.id = apply.userid and ".$where;
     $count = collection(Db::query($sqls))->toArray();
     $data = collection(Db::query($sql))->toArray();
     foreach($data as $key=>$val){
       $data[$key]['idcard'] = $val['idcard']."\t";
       //修改性别，如果是null则表示用户没有填写，所以保留为空。如果是1表示男，0表示女
       if(is_null($data[$key]['sex'])){
           $data[$key]['sex'] = "";
       }else{
           $data[$key]['sex'] = $data[$key]['sex'] ? "男" : "女";
       }
       $data[$key]['apply_create_time'] = date("Y年m月d日 H:i:s",$val['apply_create_time']);
       $data[$key]['apply_update_time'] = empty($val['apply_update_time'])? "未修改" :date("Y年m月d日 H:i:s",$val['apply_update_time']);
       $data[$key]['user_create_time'] =  date("Y年m月d日 H:i:s",$val['user_create_time']);
       switch($val['status']){
         case 1 : $data[$key]['status'] = "缴费核对中";break;
         case 2 : $data[$key]['status'] = "已录取";break;
         case 3 : $data[$key]['status'] = "报名拒绝";break;
         case 4 : $data[$key]['status'] = "待支付";break;
         case 5 : $data[$key]['status'] = "报名信息审核中";break;
       }
     }
     //组织数据
     $arr = [
       "code" =>0,
       "msg"=>'学生信息',
       "count"=>$count[0]['c'],
       "data"=>$data
     ];
     return json($arr);
   }

   /*
    * 执行修改
    */
   public function user_update(Request $request){
       //将字获取的字段内容保存到变量中
       $userid = $request->post("id"); //user.id
       $field = $request->post("field"); //传递的字段名（部分字段与数据库不对应，参考getAllUser()方法中的SQL语句中的别名）
       $value = $request->post("value"); //修改字段后的新值
       //可以编辑的字段名称（以user/list.html文件中的字段名为主）
       $is_edit = ['name','user_grade','sex','nation','phone','parenttel','qqwx','idcard','address','schoolname','schooladdress','score','bktype','major','major2','isadjust','paytype','payid','comment','reason'];
       //判断是否可以执行修改
       if(in_array($request->post("field"),$is_edit)) {
           //查看数据库中是否有报名信息
           $is_apply = Apply::where("userid", $request->post("id"))->find();
           //创建接收到的字段名称，属于user表的字段数组
           $user = ['name', 'sex', 'phone', 'idcard', 'nation', 'qqwx', 'parenttel', 'schooladdress', 'schoolname', 'score', 'address', 'user_grade'];
           //判断传递的字段名称是否属于user表，如果属于则修改user表，如果不属于则修改apply表
           if (in_array($request->post("field"), $user)) {
               //如果是性别字段，需要将男转换为数字1，女转换为数字0
               if ($field == "sex") {
                   $value = $value == "男" ? 1 : 0;
               }
               //预定义变量保存操作结果
               $res = "";
               //如果修改的字段名不是user_grade，则正常修改。（除了时间字段和user_gradeq其他字段名都相同）
               if($request->post("field") != "user_grade"){
                   $res = User::update(['id' => $request->post('id'), $field => $value]);
               }elseif($request->post("field") == "user_grade") {
                   //如果修改的是user_grade,就判断是否有报名信息，如果有报名信息一同修改user表和apply表的grade字段，如果没有报名信息就只修改user表的grade字段。
                   if ($is_apply) {
                       $res = User::update(['id' => $request->post('id'), "user_grade" => $value]) && Apply::update(['userid' => $request->post('id'), "user_grade" => $value]) ? true : false;
                   }else{
                       $res = User::update(['id' => $request->post('id'), "grade" => $value]);
                   }
               }
               //收集好修改信息，返回信息。
               if ($res) {
                   return $this->success("修改成功");
               } else {
                   return $this->error("修改失败");
               }
           } else {
               //如果有报名信息正常修改，如果没有则提示学生没有报名不能修改信息。
               if ($is_apply) {
                   if ( Apply::where("userid", $request->post('id'))->update([$request->post("field") => $request->post("value")]) ) {
                       return $this->success("修改成功");
                   } else {
                       return $this->error("修改失败");
                   }
               } else {
                   return $this->error("修改无效，该学生未完成报名！");
               }
           }
       }else{
           return $this->error("修改无效，该字段不能在这里修改！");
       }
   }

   //移入回收站
   public function del(Request $request){
       //删除是需要判断是否有apply
         $apply = Apply::where(['userid'=>$request->post('id')])->find();
         $user = User::get($request->post('id'));
         $del_comment = $request->post("del_comment");
       if($apply) {
             $arr = array(
                 "major"=>$apply['major'],
                 "bktype"=>$apply['bktype'],
                 "apply_create_time"=>strtotime($apply['create_time']),
                 "apply_update_time"=>strtotime($apply['update_time']),
                 "reason"=>$apply['reason'],
                 "comment"=>$apply['comment'],
                 "status"=>$apply['status'],
                 "paytype"=>$apply['paytype'],
                 "payid"=>$apply['payid'],
                 "type"=>$apply['type'],
                 "pay_time"=>$apply['pay_time'],
                 "major2"=>$apply['major2'],
                 "isadjust"=>$apply['isadjust'],
                 "teacher"=>$apply['teacher'],
                 "advice_note"=>$apply['advice_note'],
                 "grade"=>$apply['grade'],
                 "teacher_comment"=>$apply['teacher_comment'],
                 "teacher_id"=>$apply['teacher_id'],
                 "major_id"=>$apply['major_id'],
                 "major2_id"=>$apply['major2_id'],
                 "bktype_id"=>$apply['bktype_id'],
                 "coursetype_name"=>$apply['coursetype_name'],
                 "coursetype_id"=>$apply['coursetype_id'],
                 "name"=>$user['name'],
                 "pwd"=>$user['pwd'],
                 "sex"=>$user['sex'],
                 "phone"=>$user['phone'],
                 "idcard"=>$user['idcard'],
                 "user_create_time"=>strtotime($user['create_time']),
                 "user_update_time"=>strtotime($user['update_time']),
                 "nation"=>$user['nation'],
                 "qqwx"=>$user['qqwx'],
                 "parenttel"=>$user['parenttel'],
                 "schooladdress"=>$user['schooladdress'],
                 "schoolname"=>$user['schoolname'],
                 "score"=>$user['score'],
                 "address"=>$user['address'],
                 "del_time"=>time(),
                 "del_comment"=>$del_comment,
             );
         }else{
             $arr = array(
                 "name" => $user['name'],
                 "sex" => $user['sex'],
                 "phone" => $user['phone'],
                 "idcard" => $user['idcard'],
                 "grade" => $user['grade'],
                 "user_create_time" => strtotime($user['create_time']),
                 "user_update_time" => strtotime($user['update_time']),
                 "nation" => $user['nation'],
                 "qqwx" => $user['qqwx'],
                 "parenttel" => $user['parenttel'],
                 "schooladdress" => $user['schooladdress'],
                 "schoolname" => $user['schoolname'],
                 "score" => $user['score'],
                 "address" => $user['address'],
                 "del_time" => time(),
                 "del_comment"=>$del_comment,
             );
         }
         if (Dustbin::create($arr)) {
           User::destroy($request->post("id"));
           Apply::destroy(["userid"=>$request->post("id")]);
           \app\admin\model\Money::destroy(["userid"=>$request->post("id")]);
           $this->success("回收成功");
         } else {
           $this->error("回收失败");
         }
   }
}
